package revontuli.aMHD.datamanagement;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import revontuli.aMHD.dataclasses.Departure;

public class DepartureXMLHandler extends DefaultHandler {
	private StringBuffer buffer = new StringBuffer();
	private ArrayList<Departure> departureList;
	private Departure depart;

	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
		buffer.setLength(0);
		
		if (localName.equals("linedepartlist")) {
			departureList = new ArrayList<Departure>();
		} else if (localName.equals("departure")) {
			depart = new Departure(Integer.parseInt(atts.getValue("line_id")),
									Integer.parseInt(atts.getValue("direction")),
									Integer.parseInt(atts.getValue("stop_id")));
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) {
		if (localName.equals("departure")) {
			departureList.add(depart);
		} else if (localName.equals("departure_time")) {
			String cas = buffer.toString();
			depart.departureTime.set(Integer.parseInt(cas.substring(6, 8)),
									Integer.parseInt(cas.substring(3, 5)),
									Integer.parseInt(cas.substring(0, 2)), 1, 1, 2011);
		} else if (localName.equals("schedule_type")) {
			depart.scheduleType = Integer.parseInt(buffer.toString());
		} else if (localName.equals("exceptional_route_id")) {
			String exc = buffer.toString();
			if (exc != "") {
				depart.exceptionalRouteID = Integer.parseInt(buffer.toString());
			} else {
				depart.exceptionalRouteID = 0;
			}
		} else if (localName.equals("line_revision")) {
			depart.lineRevision = Integer.parseInt(buffer.toString());
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length) {
		buffer.append(ch, start, length);
	}
	
	public ArrayList<Departure> retrieveDepartureList() {
		return departureList;
	}

}
